﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.Collections;
using System.Xml.Serialization;

namespace ImageEnhancer
{
    [XmlRoot(Namespace = "ImageEnhancer.ImageEnhancerControl")]
    public class ImageEnhancerControl : BaseFieldControl
    {

        //protected TextBox txtFirstName;
        protected FileUpload flUpload = new FileUpload();
        protected FileUpload filenull = new FileUpload();
        protected Image ImgThumb = new Image();
        protected Button btnDelete = new Button();
        protected TextBox txtValue = new TextBox();
        protected string httppath = null;
        protected string thumbnailpath = null;
        protected Label lblMessage = new Label();
        protected Label lblMessage2 = new Label();
        protected Label lblMessage3 = new Label();
        protected string filename = null;
        protected bool hasfile = false;



        



        protected override string DefaultTemplateName
        {
           
            get { return "CustomFieldRendering"; }

        }

        public override object Value
        {

            get
            {
                
                EnsureChildControls();
                
                //return txtFirstName.Text; return web.Url + "/" + web.Lists[Listname].RootFolder.Url + "/";
                if (hasfile)
                    //if its a new file return the path to the file and the path to the thumbnail
                    return httppath + filename + "," + thumbnailpath;
                else
                {
                    if (!ImgThumb.Visible)
                    {
                        //if its going to be erease return a blank string
                        return "";
                    }
                    else
                    {   //if its not been modifie return the current string
                        return Field.FieldRenderingControl.ItemFieldValue;
                    }
                }
                return Field.FieldRenderingControl.ItemFieldValue;
            }

            set
            {

                try
                {

                    EnsureChildControls();
                    if (!value.ToString().Equals(",") || !value.ToString().Equals(""))
                    {
                        
                        ImgThumb.ImageUrl = value.ToString().Substring(value.ToString().IndexOf(',') + 1);
                        ImgThumb.Visible = true;
                        btnDelete.Visible = true;
                    }
                    else {
                        ImgThumb.Visible = false;
                        btnDelete.Visible = false;
                    }
                    
                    

                }

                catch { }

            }

        }

        public override void Focus()
        {

            EnsureChildControls();

            flUpload.Focus();

        }
        protected void afteritemaddinsert(object sender, EventArgs e)
        { 
            
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            ImgThumb.Visible = false;
            btnDelete.Visible = false;
        }
        /// <summary>
        /// Fix, once the first control its been trying to render in the Sharepoint webpage or ASCX control
        /// add the Scriptmanager control to the page in order to enable AJAX 
        /// <asp:ScriptManager runat="server" ID="ScriptManager1"></asp:ScriptManager>
        /// </summary>
        /// <param name="control"></param>
        /// <param name="index"></param>
        protected override void  AddedControl(Control control, int index)
        {
            //add the scriptmanager if there hasnt been added and its the first control on the page
            if (ScriptManager.GetCurrent(this.Page) == null && index == 0)
            {
                ScriptManager scriptMan = new ScriptManager();
                this.Controls.Add(scriptMan);
            }
 	        base.AddedControl(control, index);
        }
        
        protected override void CreateChildControls()
        {
            try{
            if (Field == null) return;

            Page.ClientScript.RegisterStartupScript(typeof(ImageEnhancerControl), "UpdatePanelFixup", "_spOriginalFormAction = document.forms[0].action; _spSuppressFormOnSubmitWrapper=true;", true);
            base.CreateChildControls();

            if (ControlMode == Microsoft.SharePoint.WebControls.SPControlMode.Display) return;


            if (ControlMode == SPControlMode.New || ControlMode == SPControlMode.Edit)
            {
                
                //Page.ClientScript.RegisterStartupScript(typeof(ImageEnhancerControl), "UpdatePanelFixup", "_spOriginalFormAction = document.forms[0].action; _spSuppressFormOnSubmitWrapper=true;", true);
                 Stream fs = null;
                 flUpload = (FileUpload)TemplateContainer.FindControl("flUpload");
                
                lblMessage = (Label)TemplateContainer.FindControl("lblMessage");
                lblMessage2 = (Label)TemplateContainer.FindControl("lblMessage2");
                lblMessage3 = (Label)TemplateContainer.FindControl("lblMessage3");
                ImgThumb = (Image)TemplateContainer.FindControl("ImgThumb");
                btnDelete = (Button)TemplateContainer.FindControl("btnDelete");
                txtValue = (TextBox)TemplateContainer.FindControl("txtValue");
                btnDelete.Click += new EventHandler(btnDelete_Click);
                try
                {
                    SPContext.Current.Item[Field.Title].Equals("null");
                }catch (Exception E) { 
                    ImgThumb.Visible = false;
                    btnDelete.Visible = false;
                }
                
                    
                if (flUpload.HasFile) {
                    fs = flUpload.PostedFile.InputStream;
                    filename = flUpload.FileName;
                    hasfile = true;
                    flUpload.EnableViewState = false;
                    flUpload = filenull;
                    flUpload.Dispose();
                    flUpload.Enabled = false;
                    //TemplateContainer.fin
                    
                }

                /*if (lblText == null) throw new NullReferenceException("lblText is null");
                if (lblMessage == null) throw new NullReferenceException("lblText is null");
                if (flUpload == null) throw new NullReferenceException("flUpload is null");*/

                flUpload.TabIndex = TabIndex;
                flUpload.CssClass = CssClass;
                flUpload.ToolTip = Field.Title + " Image";
                
                System.Collections.Specialized.NameValueCollection PictureLibrarys;
                PictureLibrarys = SharepointInformation.QueryCustType(SPContext.Current.Web.Url.ToString(), SPEncode.UrlDecodeAsUrl(SPContext.Current.List.ToString()), "CustomImageStorage");
                if (PictureLibrarys[0].Equals("False"))
                {
                    flUpload.Enabled = false;
                    lblMessage.Text = "Image cannot be uploaded as no Picture Library is associated with this list. In order to setup Picture Library, go to ";
                    lblMessage2.Text = "'List Settings - General Settings - Enhanced Image Picture Library' ";
                    lblMessage3.Text = "and select existing Picture Library";
                    lblMessage3.ForeColor = System.Drawing.Color.Red;
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    lblMessage2.ForeColor = System.Drawing.Color.Red;
                    lblMessage.Font.Bold = true;
                    lblMessage2.Font.Bold = true;
                    lblMessage3.Font.Bold = true;
                    lblMessage2.Font.Italic = true;
                    //SPUtility.Redirect("listedit.aspx?List="+listId, SPRedirectFlags.UseSource | SPRedirectFlags.RelativeToLayoutsPage, this.Context);
                }
                else {
                    flUpload.Enabled = true;
                    if(lblMessage!=null)
                        lblMessage.Visible = false;
                }
                //IF THE UPLOAD FIELD HAS INFORMATION 
                if (hasfile)
                {
                    /*SPSite site = new SPSite(Page.Request.Url.AbsoluteUri.ToString());
                    SPWeb sitex = SPContext.Current.Web;
                    SPWeb webosite = site.OpenWeb(Page.Request.Url.AbsolutePath.ToString());*/
                    //lista = webosite.GetList(Page.Request.Url.AbsolutePath.ToString()).ToString();
                    //QUERY DE LA LISTA QUE CONTIENE EL PICTURELIBRABY Y SUSTITUIR SPContext.Current.List.ToString()

                    
                    //SPContext.Current.List.ToString()
                    bool exist = false;
                    if (PictureLibrarys.HasKeys())
                        for (int i = 0; i < PictureLibrarys.Count; i++)
                        {
                            if (PictureLibrarys.GetKey(i).Equals(Field.Title))
                            {
                                exist = true;
                                break;
                            }
                        }
                    if (exist)
                    {
                        
                        thumbnailpath = SharepointInformation.UploadImage(SPContext.Current.Web.Url.ToString(), fs, PictureLibrarys[Field.Title], "", filename,SPContext.Current.Web);
                        //Full path not relative
                        //httppath = SPContext.Current.Web.Url.ToString() + "/" + SPContext.Current.Web.Lists[PictureLibrarys[Field.Title]].RootFolder.Url + "/";
                        httppath = SPContext.Current.Web.Lists[PictureLibrarys[Field.Title]].ParentWebUrl.ToString() + "/" + SPContext.Current.Web.Lists[PictureLibrarys[Field.Title]].RootFolder.Url + "/";
                        
                    }
                    else
                    {
                        
                        
                        //El valor no existe manda un mensaje al usuario para que vaya
                        thumbnailpath = "Go to List Settings - Enhanced Image Settings";
                        //list settings a configurar esta opcion.
                    }
                        
                }
            }
            //txtFirstName = (TextBox)TemplateContainer.FindControl("txtFirstName");




        }catch(Exception spe){
            int i = 0;
        }
            }

        /*protected ScriptManager findSM()
        {
            
            Page currentPg = this.Page;
            foreach (Control cntrl in currentPG.Controls)
            {
                if (cntrl is ScriptManager)
                    return ((ScriptManager)cntrl);

            }
            return new ScriptManager();
        }*/



        


        }

    }


